<template>
  <VueDraggable
    class="item"
    v-model="formItems"
    :animation="150"
    ghostClass="ghost"
    :group="{ name: 'formDraggable', pull: 'clone', put: false }"
    @update="onUpdate"
    @add="onAdd(1)"
    @remove="remove"
    @end="dragEnd"
  >
    <li v-for="item in formItems" :key="item.id" class="itemChild" draggable="true">
      {{ item.name }}
    </li>
  </VueDraggable>
</template>

<script lang="ts" setup>
import type { IFormItem } from '@/types/FormType'
// import { VueDraggable, type DraggableEvent } from 'vue-draggable-plus'
import { VueDraggable, type SortableEvent } from 'vue-draggable-plus'
import { ref } from 'vue'

const formItems = ref<IFormItem[]>([
  {
    id: 'input_1741326126867',
    type: 'input',
    name: '输入框',
    label: '城市12312',
    modelValue: 'city',
    placeholder: '请选择你的城市',
  },
])

function onUpdate() {
  console.log('update')
}
function onAdd(num: number) {
  console.log(num + 'add')
}
function remove() {
  console.log('remove')
}

const refreshKey = (index: number) => {
  const date = Number(new Date())
  const item = formItems.value[index]
  formItems.value[index].id = `${item.type}_${date}`
}

function dragEnd(e: SortableEvent) {
  const index = e.oldIndex
  console.log(index)

  if (index !== 0 && !index) throw new Error('未找到index')
  refreshKey(index)
}
</script>
